﻿using System;
using System.Collections.Generic;
using NavigationShowcase.Data;
using WinRTFramework.Common;
using WinRTFramework.Interfaces.Navigation;
using WinRTFramework.Interfaces.Navigation.ViewModel;

namespace NavigationShowcase.ViewModels
{
    public class GroupedItemsPageViewModel_Showcase : Bindable, IRequireNavigationService, ICareAboutNavigationFlow, ICareAboutSuspendResume
    {
        DelegateCommand<SampleDataGroup> _selectGroupCommand;
        public DelegateCommand<SampleDataGroup> SelectGroupCommand
        {
            get
            {
                return _selectGroupCommand = _selectGroupCommand ?? new DelegateCommand<SampleDataGroup>(OnSelectGroup);
            }
        }

        DelegateCommand<SampleDataItem> _selectItemCommand;
        public DelegateCommand<SampleDataItem> SelectItemCommand
        {
            get
            {
                return _selectItemCommand = _selectItemCommand ?? new DelegateCommand<SampleDataItem>(OnSelectItem);
            }
        }

        private IEnumerable<SampleDataGroup> _groups;
        public IEnumerable<SampleDataGroup> Groups
        {
            get { return _groups; }
            set { _groups = value; NotifyPropertyChanged(() => Groups); }
        }

        void OnSelectGroup(SampleDataGroup group)
        {
            _navigationService.Navigate<GroupDetailPageViewModel_Showcase>(group.UniqueId);
        }

        void OnSelectItem(SampleDataItem item)
        {
            _navigationService.Navigate<ItemDetailPageViewModel_Showcase>(item.UniqueId);
        }

        void LoadFromNavigationParameter(object navigationParameter)
        {
            var sampleDataGroups = SampleDataSource.GetGroups((String)navigationParameter);
            Groups = sampleDataGroups;
        }

        #region IRequireNavigationService
        INavigationService _navigationService;
        public INavigationService NavigationService
        {
            get { return _navigationService; }
            set { _navigationService = value; }
        }
        #endregion

        #region ICareAboutNavigationFlow
        public void OnNavigatedTo(object navigationParameter)
        {
            LoadFromNavigationParameter(navigationParameter);
        }

        public void OnNavigatingFrom()
        {}

        public void OnNavigatedFrom()
        {}
        #endregion

        #region ICareAboutSuspendResume
        public void Suspending()
        {
        }

        public void Resumed(object navigationParameter, ResumePreviousAppState previousAppState)
        {
            if(previousAppState == ResumePreviousAppState.Terminated)
            {
                LoadFromNavigationParameter(navigationParameter);
            }
        }
        #endregion
    }
}
